//
//  OAuthViewController.swift
//  Weibo
//
//  Created by .. on 16/4/27.
//  Copyright © 2016年 Lizhuo. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    let WB_App_Key = "926094680"
    let WB_App_Secret = "83b3ea2279c1d8ede0759c0e68ab6a62"
    let WB_redirect_uri = "http://www.baidu.com"
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //0.初始化导航条
        navigationItem.title = "登录"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(OAuthViewController.close))
        
        //1.获取未授权的RequestToken
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_App_Key)&redirect_uri=\(WB_redirect_uri)"
        let url = NSURL(string: urlStr)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: - 懒加载
    private lazy var webView: UIWebView = {
       let webView = UIWebView()
        webView.delegate = self
        return webView
    }()
}

extension OAuthViewController: UIWebViewDelegate {
    //授权成功: http://www.baidu.com/?code=6f0ef42c30a9c4b757c7b8be2ec4b0e0
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print(request.URL?.absoluteString)
        //1.判断是否是授权回调页面，如果不是就继续加载
        let urlStr = request.URL!.absoluteString
        if !urlStr.hasPrefix(WB_redirect_uri) {
            //继续加载
            return true
        }
        
        //2.判断是否授权成功
        let codeStr = "code="
        if request.URL!.query!.hasPrefix(codeStr) { //授权成功
            //1.取出已经授权的RequestToken
            //codeStr.endIndex是从“code＝”开始以后的index
            let code = request.URL!.query?.substringFromIndex(codeStr.endIndex)
            //2.利用已经授权的RequestToken换取AccessToken
            loadAccessToken(code!)
        } else { //取消授权
            //关闭界面
            close()
        }
        
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        //提示用户正在加载
        SVProgressHUD.showInfoWithStatus("正在加载...", maskType: SVProgressHUDMaskType.Black)
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭提示
        SVProgressHUD.dismiss()
    }
    
    /**
     换取AccessToken
     
     - parameter code: <#code description#>
     */
    private func loadAccessToken(code: String) {
        //1.定义路径
        let path = "oauth2/access_token"
        //2.封装参数
        let params = ["client_id": WB_App_Key,
                      "client_secret": WB_App_Secret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": WB_redirect_uri]
        //3.发送POST请求
        NetworkTools.sharedNetworkTools().POST(path, parameters: params, success: { (_, JSON) in
            //1.字典转模型
            let account = UserAccount(dict: JSON as! [String: AnyObject])
            
            //2.获取用户信息
            account.loadUserInfo {(account, error) -> () in
                if account != nil {
                    account?.saveAccount()
                    //去欢迎界面
                    NSNotificationCenter.defaultCenter().postNotificationName(LZSwitchRootViewController, object: false)
                    return
                }
                SVProgressHUD.showInfoWithStatus("网络不给力", maskType: SVProgressHUDMaskType.Black)
                
            }

            //2.归档模型
//            account.saveAccount()
            }) { (_, error) in
                print(error)
        }
    }
    
}
